// 猜数字游戏

package Leetcode;

import java.util.HashMap;
import java.util.Map;

class Solution_299 {
    public String getHint(String secret, String guess) {
        int length = secret.length();
        int bulls = 0;
        int cowsAndBulls = 0;
        Map<Character, Integer> map = new HashMap<>();

        // 第一次遍历计算bulls并计数secret的数字
        for (int i = 0; i < length; i++) {
            if (secret.charAt(i) == guess.charAt(i))
                bulls++;

            if (map.containsKey(secret.charAt(i))) {
                map.put(secret.charAt(i), map.get(secret.charAt(i)) + 1);
            } else {
                map.put(secret.charAt(i), 1);
            }
        }

        // 第二次遍历根据map计算bulls和cows的总数
        for (int i = 0; i < length; i++) {
            if (map.containsKey(guess.charAt(i))) {
                cowsAndBulls++;
                if (map.get(guess.charAt(i)) == 1)
                    map.remove(guess.charAt(i));
                else
                    map.put(guess.charAt(i), map.get(guess.charAt(i)) - 1);
            }
        }
        return bulls + "A" + (cowsAndBulls - bulls) + "B";
    }
}